package net.babypai.views;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Matrix;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.widget.ImageView;

public class MyImageView extends ImageView {

	public MyImageView(Context context, AttributeSet attrs) {
		super(context, attrs);
		setScaleType(ScaleType.CENTER_CROP);
	}

	public MyImageView(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		setScaleType(ScaleType.CENTER_CROP);
	}

	public MyImageView(Context context) {
		super(context);
		setScaleType(ScaleType.CENTER_CROP);
	}

	@Override
	protected boolean setFrame(int l, int t, int r, int b) {
		if (getDrawable() == null) {
			return super.setFrame(l, t, r, b);
		}
		Matrix matrix = getImageMatrix();
		float scaleWidth = getWidth()
				/ (float) getDrawable().getIntrinsicWidth();
		float scaleHeight = getHeight()
				/ (float) getDrawable().getIntrinsicHeight();
		float scaleFactor = (scaleWidth > scaleHeight) ? scaleWidth
				: scaleHeight;
		matrix.setScale(scaleFactor, scaleFactor, 0, 0);
		if (scaleFactor == scaleHeight) {
			float tanslateX = ((getDrawable().getIntrinsicWidth() * scaleFactor) - getWidth()) / 2;
			matrix.postTranslate(-tanslateX, 0);
		}
		setImageMatrix(matrix);
		return super.setFrame(l, t, r, b);
	}

	@SuppressLint("FloatMath")
	@Override
	protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
		Drawable d = getDrawable();

		if (d != null) {
			int width = MeasureSpec.getSize(widthMeasureSpec) - 5;
			int height = (int) Math.ceil((float) width
					* (float) d.getIntrinsicHeight()
					/ (float) d.getIntrinsicWidth());
			setMeasuredDimension(width, height);
		} else {
			super.onMeasure(widthMeasureSpec, heightMeasureSpec);
		}
	}
}